package com.study.cms.auth.interceptor;

import com.study.cms.auth.annotation.RonghuanetPermission;
import com.study.cms.auth.mapper.PermissionMapper;
import com.study.cms.basic.utils.BasicMap;
import com.study.cms.org.domain.Emp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    private PermissionMapper permissionMapperon;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");

        //判空
        if(StringUtils.isEmpty(token)){
            response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }

        // 获取登录用户信息
        Object loginUser = BasicMap.loginMap.get(token);

        // 不为空就说明登录过,就放行,否则就拦截
        if(Objects.isNull(loginUser)){
            response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }

        //权限拦截
        Emp emp=(Emp) loginUser;

        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod=(HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            RonghuanetPermission annotation = method.getAnnotation(RonghuanetPermission.class);
            if(Objects.isNull(annotation)){
                return true;

            }
            //拿到当前用户所拥有的所有权限
            List<String> sns = permissionMapperon.getsnsbyEmpid(emp.getId());

            String sn = method.getDeclaringClass().getSimpleName()+":"+method.getName();
            if(!sns.contains(sn)){
                response.getWriter().write("{\"success\":false,\"message\":\"noPermission\"}");
                return false;
            }

        }





        return true;
    }

}

